package com.softa.service.system.impl;

import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageInfo;
import com.softa.dao.dto.SysMessageDTO;
import com.softa.dao.mapper.base.SysMessageMapper;
import com.softa.dao.mapper.relation.system.SysMessageRelationMapper;
import com.softa.dao.model.SysMessage;
import com.softa.service.system.SysMessageService;
import com.softa.vo.DataGridRequest;
import com.softa.vo.QueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysMessageServiceImpl implements SysMessageService {

    @Autowired
    private SysMessageRelationMapper sysMessageRelationMapper;

    @Autowired
    private SysMessageMapper sysMessageMapper;

    @Override
    public PageInfo<SysMessageDTO> queryProductTypeByParam(DataGridRequest request, final QueryRequest queryRequest) {
	  PageInfo<SysMessageDTO> page = request.startPagePlugin().doSelectPageInfo(new ISelect() {
		@Override
		public void doSelect() {
                sysMessageRelationMapper.selectByCondition(queryRequest);
		}
	  });
	  return  page;
    }

    @Override
    public int selectCountByCondition() {
        final QueryRequest queryRequest = new QueryRequest();
        Long result = sysMessageRelationMapper.selectCountByCondition(queryRequest);
        return result.intValue();
    }

    @Override
    public Integer updateRead(List<Long> ids) {
        for (Long id : ids) {
            SysMessage sysMessage = sysMessageMapper.selectByPrimaryKey(id);
            sysMessage.setStatus(true);
            sysMessageMapper.updateByPrimaryKeySelective(sysMessage);
        }
        return 0;
    }

    @Override
    public Integer deleteMessage(List<Long> ids) {
        for (Long id : ids) {
            sysMessageMapper.deleteByPrimaryKey(id);
        }
        return 0;
    }

    public int saveMessage(Long userId, String content) {
        SysMessage sysMessage = new SysMessage();
        sysMessage.setReceiverId(userId);
        sysMessage.setContent(content);
        sysMessage.setStatus(false);
        sysMessage.setCreateTime(new Date());
        return sysMessageMapper.insertSelective(sysMessage);
    }

    @Override
    public Long getMessageCountByParam(Long userId) {
        QueryRequest queryRequest = new QueryRequest();
        queryRequest.getParams().put("receiverId", userId);
        queryRequest.getParams().put("status", "0");
        return sysMessageRelationMapper.selectCountByCondition(queryRequest);
    }
}
